#include "support.h"
			
int kbhit()			 //为linux添加kbhit函数，返回1表示有按键被按下，返回0表示无按键被按下
{  
	struct termios oldt, newt;  
	int ch;  
	int oldf;  
	tcgetattr(STDIN_FILENO, &oldt);  
	newt = oldt;  
	newt.c_lflag &= ~(ICANON | ECHO);  
	tcsetattr(STDIN_FILENO, TCSANOW, &newt);  
	oldf = fcntl(STDIN_FILENO, F_GETFL, 0);  
	fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);  
	ch = getchar();  
	tcsetattr(STDIN_FILENO, TCSANOW, &oldt);  
	fcntl(STDIN_FILENO, F_SETFL, oldf);  
	if(ch != EOF)  
	{  
		ungetc(ch, stdin);  
		return 1;  
	}  
	return 0;  
}

int getch()				//为linux添加getch()函数
{
	int c=0;
	struct termios org_opts, new_opts;
	int res=0;
	res=tcgetattr(STDIN_FILENO, &org_opts);
	assert(res==0);
	memcpy(&new_opts, &org_opts, sizeof(new_opts));
	new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
	tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
	c=getchar();
	res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
	assert(res==0);
	return c;
}

int readKeyboard(int cmd)		//读键盘函数,cmd若为0则无按键按下时返回HOLD，若为1在无按键按下时等待按键
{
	int Ckey=0;
	char gkey=' ';
	if (cmd==1) 
	{
		Ckey=1;
	}
	else if (cmd==0)
	{
		Ckey=kbhit();
	}
	else 
	{
		return (-1);
	}
	if (Ckey==1)
	{
		gkey=getch();
		Ckey=kbhit();
		if(gkey==27)		//若按键读取到首个数据是27，则表明是方向键
		{
			getchar();	//吞掉该读取的第二位91
			gkey=getch();	//识别该读取到第三位65-68代表四个方向
			if(gkey==65)
				return UP;
			else if(gkey==66)
				return DOWN;
			else if(gkey==68)
				return LIFT;
			else if(gkey==67)
				return RIGHT;
			getchar();	//吞掉最后一位10
		}
		else
		{
			if(gkey=='w'||gkey=='W')
				return UP;
			else if(gkey=='s'||gkey=='S')
				return DOWN;
			else if(gkey=='a'||gkey=='A')
				return LIFT;
			else if(gkey=='d'||gkey=='D')
				return RIGHT;
			else if(gkey=='p'||gkey=='P')
				return PAUSE;
			else if(gkey=='l'||gkey=='L')
				return LEAVE;
			else if(gkey=='y'||gkey=='Y')
				return Y;
			else if(gkey=='n'||gkey=='N')
				return N;
			else if(gkey==' ')
				return SPACE;
			else
				return HOLD;	
		}
	}
}

void clearScreen()		//清屏
{
	system("clear");	//linux
//	system("cls");		//windows
}

void delay_ms(int t)		//按毫秒延时
{
	usleep(t*1000);		//linux
//	Sleep(t);		//windows
}
